<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Product;
use App\Services\FileStoreService;
use App\Services\RedisService;
use function foo\func;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class ProductController extends Controller
{

    private $category;
    private $product;

    public function __construct(Category $category, Product $product)
    {
        $this->category = $category;
        $this->product = $product;
    }

    public function add(Request $request){

        $validator = Validator::make($request->all(), [
            'category_id' => 'required|integer|min:1',
            'name' => 'required|string|min:6,max:32',
            'buying_point' => 'string|max:140}',
            'unit_id' => 'integer|min:1',
            'brand_id' => 'integer|min:1',
            'specifications' => 'string|max:255',
            'min_order' => 'integer|min:1',
            'shop_price' => 'required|between:1,9999999|gt:cost_price',
            'market_price' => 'required|between:1,9999999|gt:cost_price',
            'cost_price' => 'required|between:1,9999999',
            'inventory_num' => 'required|integer|between:1,9999',
            'warning_num' => 'required|integer|between:1,100',
            'product_code' => 'alpha_dash|size:20',
            'bar_code' => 'alpha|size:20',
            'inventory_code' => 'numeric|size:20',
            'image_url' => ['required','url',function($attribute, $value, $fail){

                if(!in_array(substr($value,'-4'),['.jpg','.png','.gif'])){
                    $fail($attribute.' 不是图片地址.');
                }
            }]
        ]);

        if ($validator->fails()) {


            return $this->error($validator->errors());
        }

        if(!$this->category->isExitsById($request['category_id'])){

            return $this->error('父类不存在');

        }



        $model = $this->product->create($request->all());


        return $this->success($model->id);

    }


    public function getDetail($id){

        $result = Redis::get ("product:{$id}");
        if($result){
            return $this->success(json_decode($result,true));
        }

        $model = $this->product->find($id);

        if(empty($model)){
            return $this->error('该id不存在');
        }

        $result = $model->toArray();

        $result['category'] = $model->category->toArray();

        Redis::set ("product:{$id}",json_encode($result));

        return $this->success($result);
    }


    public function getDetail1($id){

        $result = Redis::hgetall("product1:{$id}");

        if($result){
            return $this->success($result);
        }

        $model = $this->product->find($id);

        if(empty($model)){
            return $this->error('该id不存在');
        }

        $result = $model->toArray();

        foreach ($result as $key => $value){
            Redis::hset("product1:{$id}",$key, $value);
        }

        return $this->success($result);
    }

    public function update(Request $request, $id){

        return 'update'.$id;
    }

    public function delete($id){
        return 'delete'.$id;
    }

    public function getUnit(){
        return 'unit';
    }

    public function getBrand(){
        return 'brand';
    }

    public function uploadImage(Request $request){

        $validator = Validator::make($request->all(), [
            'avatar' => 'required|image',
        ]);

        if ($validator->fails()) {


            return $this->error($validator->errors());
        }

        $path = $request->file('avatar')->storeAs('uploads',date("YmdHis").rand(1000,9999).'.jpg');

        $result = 'http://www.shop.com/'.$path;

        return $this->success($result);
    }


    public function uploadQiNiu(Request $request,FileStoreService $fileStoreService){

        $validator = Validator::make($request->all(), [
            'avatar' => 'required|image',
        ]);

        if ($validator->fails()) {

            return $this->error($validator->errors());
        }


        $result = $fileStoreService->save('demo/'.time().'.'
            .$request->file('avatar')->getClientOriginalExtension(),
            $request->file('avatar')->getRealPath() );

        if(empty($result)){
            return $this->error("上传失败");
        }

        return $this->success($result);

    }

    public function getRanking(){

        $result = Redis::zrevrange ("ranking",0 ,4 );


        return $this->success($result);

    }


    public function sell($id){

        $result = Redis::zincrby("ranking",1 ,$id);

        return $this->success(['id' => $id, 'num' => $result]);

    }
}
